package com.xiaohudie.thread;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @Author xiao hu die
 * @Date 2022/2/21 19:46
 * @Version 1.0
 */
public class Test14 {
    public static void main(String[] args) {
        List<String> list =new ArrayList<>();

        Thread thread = new Thread(new Consumer(list));
        Thread thread1 = new Thread(new Product(list));
        thread.start();
        thread1.start();
    }
  static  class Consumer implements Runnable{
      List<String> list =new ArrayList<>();
      public Consumer(List list) {
          this.list =list;
      }
    /**对这个仓库上锁*/

        @Override
      public void run() {
          synchronized (list) {
              while (true) {
                  /**如果仓库是空的，就生产一个*/
                  if (list.isEmpty()) {
                      UUID uuid = UUID.randomUUID();
                      String a = String.valueOf(uuid);
                      System.out.println("生产一个+" + a);
                      list.add(a);
                      /**生产一个之后就唤醒消费者消费*/
                      list.notifyAll();
                  }
                  /**代码走到这就说明仓库不是空的*/
                  try {
                      list.wait();
                  } catch (InterruptedException e) {
                      e.printStackTrace();
                  }
              }
          }
      }
  }
    static class Product implements Runnable{
   List<String> list =new ArrayList<>();
        public Product(List list) {
         this.list =list;
        }

        @Override
        public void run() {
            synchronized (list){
              while (true){
                if (list.isEmpty()){
                    try {
                        list.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                /**能走到这说明不是空的*/
                String remove = list.remove(0);
                System.out.println("消费一个+" +remove);
                list.notifyAll();
            }
        }
    }
    }
}
